package cn.com.jrj.base.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang.StringUtils;

public class StringUtil {
	private static final StringUtil instance = new StringUtil();

	public static StringUtil getInstance() {
		return instance;
	}

	public String digestMD5(String src) {
		if (src == null)
			return null;
		String result = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] srcByte = src.getBytes("UTF-8");
			md5.update(srcByte);
			byte[] resultByte = md5.digest();
			int j = resultByte.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = resultByte[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			result = new String(str);
		} catch (NoSuchAlgorithmException ex) {
		} catch (UnsupportedEncodingException ex) {
		}
		return result;
	}

	public static int getInt(String s) {
		int i = 0;
		if (s == null)
			return 0;
		try {
			i = Integer.parseInt(s);
		} catch (Exception e) {
			return 0;
		}
		return i;
	}

	public String subStr(String s, int max) {
		if (StringUtils.isEmpty(s))
			return null;

		max = s.length() < max ? s.length() : max;
		return s.substring(0, max);
	}
	
	public String cleanTag(String html){
		String curstr=html;  
		  int pos1,pos2;
		  int curstrLen=0;
		  while(curstr.indexOf("<")!=-1 && curstr.indexOf(">")!=-1)
		  {
		   curstrLen=curstr.length();
		   pos1=curstr.indexOf("<");
		   pos2=curstr.indexOf(">",pos1);
		   if(pos1>pos2)
		   {
		    curstr=curstr.substring(0,pos2-1)+curstr.substring(pos1+1,curstrLen);
		   }
		   else
		   {
		    curstr=curstr.substring(0,pos1)+curstr.substring(pos2+1,curstrLen);
		   }   
		  } 
		  return curstr;
	}
	/**
	 * 取字符串的前toCount个字符,如果遇到汉字截取半个的,按一个算.
	 * @param str   被处理字符串
	 * @param toCount 截取长度
	 * @param isellipsis 是否显示省略号
	 * @return
	 */
	public static String substring(String str, int toCount,String isellipsis){
		  if(toCount==0) return str;
	      int reInt = 0;
	      String reStr = "";
	      if (str == null)
	        return "";
	      char[] tempChar = str.toCharArray();
	      for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++) {
	        String s1 = str.valueOf(tempChar[kk]);
	        byte[] b = s1.getBytes();
	        reInt += b.length;
	        reStr += tempChar[kk];
	      }
	      int cl = str.getBytes().length;
	      int ct = reStr.getBytes().length;
	      if (cl>ct && isellipsis.equals("0")){
	        reStr += "...";
	      }
	      return reStr;
	    }

}

